import 'dart:convert';
import 'dart:collection';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter_app/utils/code.dart';
import 'package:flutter_app/utils/config.dart';
import 'package:flutter_app/utils/utils.dart';
import 'package:flutter_app/utils/interceptors/error_interceptor.dart';
import 'package:flutter_app/utils/interceptors/header_interceptor.dart';
import 'package:flutter_app/utils/interceptors/response_interceptor.dart';
import 'package:flutter_app/utils/interceptors/token_interceptor.dart';

final HttpManager httpManager = HttpManager();

///http请求
class HttpManager {
  static const CONTENT_TYPE_JSON = "application/json";
  static const CONTENT_TYPE_FORM = "application/x-www-form-urlencoded";

  Dio _dio = Dio();

  BuildContext _context;

  bool _isShowLoading = false;

  HttpManager() {
    _dio.interceptors.add(new HeaderInterceptors());

    _dio.interceptors.add(new TokenInterceptors());

    _dio.interceptors.add(new ErrorInterceptors(_dio));

    _dio.interceptors.add(new ResponseInterceptors());
  }

  ///发起网络请求
  ///[ context] 用来控制加载动画的显示和关闭
  ///[ url] 请求url
  ///[ params] 请求参数
  ///[ header] 外加头
  ///[ option] 配置
  netFetch(BuildContext context, url, params, Map<String, dynamic> header,
      Options option) async {
    if (!_isShowLoading) {
      _isShowLoading = true;
      _context = context;
      Utils.showLoadingDialog(_context);
    }

    Map<String, dynamic> headers = new HashMap();
    if (header != null) {
      headers.addAll(header);
    }

    if (option != null) {
      option.headers = headers;
    } else {
      option = new Options(method: "get");
      option.headers = headers;
    }

    Response response;
    try {
      response = await _dio.request(url, data: params, options: option);
      closeloading();
    } on DioError catch (e) {
      Response errorResponse;
      String errorMsg = '';
      if (e.response != null) {
        errorResponse = e.response;
        errorMsg = json.decode(e.response.toString())['message'];
      } else {
        errorResponse = new Response(statusCode: 666);
      }
      if (e.type == DioErrorType.CONNECT_TIMEOUT ||
          e.type == DioErrorType.RECEIVE_TIMEOUT) {
        errorResponse.statusCode = Code.NETWORK_TIMEOUT;
      }

      closeloading();
      return new ResultData(
          Code.errorHandleFunction(errorResponse.statusCode, errorMsg),
          false,
          errorResponse.statusCode);
    } finally {
      closeloading();
    }
    return response.data;
  }

  void closeloading() {
    if (_isShowLoading) {
      Navigator.pop(_context);
      _context = null;
      _isShowLoading = false;
    }
  }
}
